package com.yd.sdk.max;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.adjust.sdk.Adjust;
import com.adjust.sdk.AdjustAdRevenue;
import com.adjust.sdk.AdjustConfig;
import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxAdFormat;
import com.applovin.mediation.MaxAdListener;
import com.applovin.mediation.MaxAdRevenueListener;
import com.applovin.mediation.MaxAdViewAdListener;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.MaxReward;
import com.applovin.mediation.MaxRewardedAdListener;
import com.applovin.mediation.ads.MaxAdView;
import com.applovin.mediation.ads.MaxInterstitialAd;
import com.applovin.mediation.ads.MaxRewardedAd;
import com.applovin.sdk.AppLovinSdk;
import com.applovin.sdk.AppLovinSdkConfiguration;
import com.applovin.sdk.AppLovinSdkUtils;
import com.unity3d.player.MyUnityPlayerActivity;
import com.yd.sdk.ad.AdAbstractClass;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

public class AdMaxImp extends AdAbstractClass implements MaxAdListener, MaxAdViewAdListener, MaxRewardedAdListener , MaxAdRevenueListener {
    private String AD_UNIT_ID_banner = "";
    private String AD_UNIT_ID_reward= "";
    private String AD_UNIT_ID_inter = "";
    private Activity _activity;
    private Handler _handler;

    private MaxAdView _adView;
    private MaxInterstitialAd _interstitialAd;
    private MaxRewardedAd _rewardedAd;
    private int _retryAttempt;

    @Override
    public void onCreate(Activity activity, Bundle savedInstanceState) {
        _activity = activity;
        _handler = new Handler();
         // Make sure to set the mediation provider value to "max" to ensure proper functionality
            AppLovinSdk.getInstance( _activity ).setMediationProvider( "max" );
            AppLovinSdk.initializeSdk( _activity, new AppLovinSdk.SdkInitializationListener() {
                @Override
                public void onSdkInitialized(final AppLovinSdkConfiguration configuration)
                {
                    // AppLovin SDK is initialized, start loading ads
                }
            } );



        //RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("1D6E1F276EFB438DA95F8042724DAB27"))
    }

    @Override
    public void onPause() {

    }

    @Override
    public void onResume() {

    }

    @Override
    public void onDestroy() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantRes) {

    }

    @Override
    public void SetTestDeviceIds(String ids) {

    }

    @Override
    public void SetAdIds(String bannerId, String interstitialId, String rewardId) {
        _handler.post(new Runnable() {
            @Override
            public void run() {
                AD_UNIT_ID_banner = bannerId;
                AD_UNIT_ID_inter = interstitialId;
                AD_UNIT_ID_reward = rewardId;
                Log.e("AdImp:" ,AD_UNIT_ID_banner+"," + AD_UNIT_ID_inter +","+ AD_UNIT_ID_reward);
                //如果给的横幅id不为空就初始化
                if(!"".equals(AD_UNIT_ID_banner))
                    createBannerAd();

                if(!"".equals(AD_UNIT_ID_inter))
                    createInterstitialAd();

                if(!"".equals(AD_UNIT_ID_reward))
                    createRewardedAd();
            }
        });
    }

    private void createInterstitialAd() {
        _interstitialAd = new MaxInterstitialAd(AD_UNIT_ID_inter, _activity);
        _interstitialAd.setListener(this);
        _interstitialAd.setRevenueListener(this);

        // Load the first ad
        _interstitialAd.loadAd();
    }

    private void createBannerAd()
    {
        _adView = new MaxAdView( AD_UNIT_ID_banner, _activity );
        _adView.setListener( this );
        _adView.setRevenueListener(this);
        int heightDp = MaxAdFormat.BANNER.getAdaptiveSize( _activity ).getHeight();
        int heightPx = AppLovinSdkUtils.dpToPx( _activity, heightDp );
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        lp.gravity = Gravity.BOTTOM;
//        Display display = _activity.getWindowManager().getDefaultDisplay();
//        DisplayMetrics outMetrics = new DisplayMetrics();
//        display.getMetrics(outMetrics);
        //_adView.setY(_adView.getHeight());
        _adView.setBackgroundColor(0);

        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        ((MyUnityPlayerActivity) _activity).GetUnityPlayer().addView(_adView,lp);

        // Load the ad
        _adView.loadAd();
    }

    private void createRewardedAd()
    {
        _rewardedAd = MaxRewardedAd.getInstance( AD_UNIT_ID_reward, _activity );
        _rewardedAd.setListener( this );
        _rewardedAd.setRevenueListener(this);
        _rewardedAd.loadAd();
    }

    @Override
    public void LoadedAd(AdType adType) {

    }

    @Override
    public boolean IsAdAvailable(AdType adType) {

        if(adType == AdType.Banner)
        {
            return false;
        }else if(adType == AdType.Interstitial)
        {
            return _interstitialAd!=null &&_interstitialAd.isReady();
        }else if(adType == AdType.Reward)
        {
            return _rewardedAd!=null &&_rewardedAd.isReady();
        }else
        {
            return false;
        }

    }

    @Override
    public void ShowBanner(BannerPos pos) {

    }

    @Override
    public void ShowInterstitial() {

        _handler.post(new Runnable() {
            @Override
            public void run() {
                if ( _interstitialAd.isReady()) {
                    _interstitialAd.showAd();
                }
            }
        });
    }
    private boolean _isVideoReward = false;
    @Override
    public void ShowReward() {

        _handler.post(new Runnable() {
            @Override
            public void run() {
                if ( _rewardedAd.isReady() ) {
                    _rewardedAd.showAd();
                    _isVideoReward = false;
                }
            }
        });
    }

    @Override
    public void HideAd(AdType adType) {

    }

    //////////////////MAX回调/////////////////////////////////////////

    @Override
    public void onAdLoaded(MaxAd ad) {

        _retryAttempt = 0;
        String adUnitId = ad.getAdUnitId();
        if(AD_UNIT_ID_inter.equals(adUnitId))
        {
            Log.e("AdMaxImp","AD_UNIT_ID_inter:onAdLoaded");
        }else if(AD_UNIT_ID_banner.equals(adUnitId))
        {
            Log.e("AdMaxImp","AD_UNIT_ID_banner:onAdLoaded");
            AppLovinSdkUtils.Size adViewSize = ad.getSize();
            int widthDp = adViewSize.getWidth();
            int heightDp = adViewSize.getHeight();

            Display display = _activity.getWindowManager().getDefaultDisplay();
            DisplayMetrics outMetrics = new DisplayMetrics();
            display.getMetrics(outMetrics);
            if(hasNavigationBar(_activity))
            {
                Log.e("AdMaxImp","AD_UNIT_ID_banner1:"+outMetrics.heightPixels + getNavigationBarHeight(_activity));
                _adView.setY(outMetrics.heightPixels + getNavigationBarHeight(_activity) - heightDp);
            }else
            {
                Log.e("AdMaxImp","AD_UNIT_ID_banner2:"+outMetrics.heightPixels);
                _adView.setY(outMetrics.heightPixels);
            }

        }else if(AD_UNIT_ID_reward.equals(adUnitId)) {
            Log.e("AdMaxImp","AD_UNIT_ID_reward:onAdLoaded");
        }

    }


    public static boolean hasNavigationBar(Context var0) {
        boolean var1 = false;
        int var2;
        Resources var4;
        if((var2 = (var4 = var0.getResources()).getIdentifier("config_showNavigationBar", "bool", "android")) > 0) {
            var1 = var4.getBoolean(var2);
        }

        try {
            Class var5;
            String var6 = (String)(var5 = Class.forName("android.os.SystemProperties")).getMethod("get", new Class[]{String.class}).invoke(var5, new Object[]{"qemu.hw.mainkeys"});
            if("1".equals(var6)) {
                var1 = false;
            } else if("0".equals(var6)) {
                var1 = true;
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return var1;
    }

    public static int getNavigationBarHeight(Context var0) {
        boolean var1 = ViewConfiguration.get(var0).hasPermanentMenuKey();
        int var2;
        return (var2 = var0.getResources().getIdentifier("navigation_bar_height", "dimen", "android")) > 0 && !var1?var0.getResources().getDimensionPixelSize(var2):0;
    }


    @Override
    public void onAdDisplayed(MaxAd ad) {

    }

    @Override
    public void onAdHidden(MaxAd ad) {
        String adUnitId = ad.getAdUnitId();
        if(AD_UNIT_ID_inter.equals(adUnitId))
        {
            // Interstitial ad failed to load
            _interstitialAd.loadAd();
            OnAdClosed(AdType.Interstitial,"");
        }else if(AD_UNIT_ID_banner.equals(adUnitId))
        {

        }else if(AD_UNIT_ID_reward.equals(adUnitId)) {
            _rewardedAd.loadAd();
            if(!_isVideoReward)
                OnAdClosed(AdType.Reward,"Hidden");
        }
    }

    @Override
    public void onAdClicked(MaxAd ad) {

    }

    @Override
    public void onAdLoadFailed(String adUnitId, MaxError error) {

        // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds)
        long delayMillis = TimeUnit.SECONDS.toMillis( (long) Math.pow( 2, Math.min( 6, _retryAttempt ) ) );

        new Handler().postDelayed( new Runnable()
        {
            @Override
            public void run()
            {
                if(AD_UNIT_ID_inter.equals(adUnitId))
                {
                    Log.e("AdMaxImp","AD_UNIT_ID_reward:AD_UNIT_ID_inter" +error.getMessage());
                    // Interstitial ad failed to load
                    _interstitialAd.loadAd();
                }else if(AD_UNIT_ID_banner.equals(adUnitId))
                {
                    Log.e("AdMaxImp","AD_UNIT_ID_reward:onAdLoadFailed" + error.getMessage());
                }else if(AD_UNIT_ID_reward.equals(adUnitId)) {
                    Log.e("AdMaxImp","AD_UNIT_ID_reward:onAdLoadFailed" + error.getMessage());
                    _rewardedAd.loadAd();
                }
            }
        }, delayMillis );


        _retryAttempt++;

    }

    @Override
    public void onAdDisplayFailed(MaxAd ad, MaxError error) {
        String adUnitId =  ad.getAdUnitId();
        if(AD_UNIT_ID_inter.equals(adUnitId))
        {
            //插屏
            // Interstitial ad failed to display. AppLovin recommends that you load the next ad.
            _interstitialAd.loadAd();
        }else if(AD_UNIT_ID_banner.equals(adUnitId))
        {

        }else if(AD_UNIT_ID_reward.equals(adUnitId)) {
            _rewardedAd.loadAd();
        }

    }

    @Override
    public void onAdExpanded(MaxAd ad) {

    }

    @Override
    public void onAdCollapsed(MaxAd ad) {

    }

    @Override
    public void onRewardedVideoStarted(MaxAd ad) {

    }

    @Override
    public void onRewardedVideoCompleted(MaxAd ad) {

    }

    @Override
    public void onUserRewarded(MaxAd ad, MaxReward reward) {
        Log.e("AdMaxImp",reward.getAmount() +","+reward.getLabel());
        OnAdClosed(AdType.Reward,reward.getAmount() +","+reward.getLabel());
        _isVideoReward = true;
    }

    @Override
    public void onAdRevenuePaid(MaxAd ad) {
        AdjustAdRevenue adjustAdRevenue = new AdjustAdRevenue( AdjustConfig.AD_REVENUE_APPLOVIN_MAX);
        adjustAdRevenue.setRevenue(ad.getRevenue(), "USD");
        adjustAdRevenue.setAdRevenueNetwork(ad.getNetworkName());
        adjustAdRevenue.setAdRevenueUnit(ad.getAdUnitId());
        adjustAdRevenue.setAdRevenuePlacement(ad.getPlacement());

        Adjust.trackAdRevenue( adjustAdRevenue);
    }
}
